import 'package:flutter/material.dart';
import 'package:getx_scaffold/getx_scaffold.dart';
import 'package:fl_chart/fl_chart.dart';
import 'diet_record_logic.dart';
import '../../../gen/assets.gen.dart';
import '../../../common/styles/theme_manager.dart';
import '../../../widgets/fixed_header_with_tabs.dart';
import 'diet_statistics/routes.dart';
import '../calendar/simple_calendar_view.dart';

/// 饮食记录详情页面
class DietRecordView extends GetView<DietRecordLogic> {
  const DietRecordView({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.black,
      body: SafeArea(
        child: Column(
          children: [
            // 固定的头部（标题 + 日周月切换）
            Obx(() => FixedHeaderWithTabs(
                  title: '饮食',
                  selectedIndex: controller.state.selectedPeriod.value,
                  onTabChanged: (index) => controller.changePeriod(index),
                  actions: [
                    IconButton(
                      icon: const Icon(Icons.stacked_bar_chart,
                          color: Colors.white),
                      onPressed: () {
                        Get.toNamed(DietStatisticsRoutes.dietStatistics);
                      },
                    ),
                    IconButton(
                      icon: Assets.status.calendar.image(
                        width: 24.w,
                        height: 24.w,
                        color: Colors.white,
                      ),
                      onPressed: () async {
                        final selectedDate = await Get.to(() =>
                            const SimpleCalendarView(
                                calendarType: CalendarType.food));
                        if (selectedDate != null && selectedDate is String) {
                          controller.loadDataByDate(selectedDate);
                        }
                      },
                    ),
                  ],
                )),
            // 可滚动的内容区域
            Expanded(
              child: Stack(
                children: [
                  // 渐变背景
                  Positioned(
                    top: 0,
                    left: 0,
                    right: 0,
                    height: 200.h,
                    child: Container(
                      decoration: BoxDecoration(
                        gradient: LinearGradient(
                          begin: Alignment.topRight,
                          end: Alignment.bottomRight,
                          colors: ThemeManager.to.backgroundGradientColors,
                          stops: const [0.1, 0.3, 0.7, 1.0],
                        ),
                      ),
                    ),
                  ),
                  // 主要内容
                  SingleChildScrollView(
                    child: Column(
                      children: [
                        SizedBox(height: 20.h),

                        // 卡路里摄入卡片
                        _buildCalorieCard(),


                        SizedBox(height: 16.h),

                        // 今日能量平衡卡片（包含饮食摄入和活动消耗）
                        _buildEnergyBalanceCard(),

                        SizedBox(height: 16.h),

                        // 关于饮食卡片
                        _buildAboutDietCard(),

                        SizedBox(height: 32.h),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建卡路里摄入卡片
  Widget _buildCalorieCard() {
    return Builder(
      builder: (context) => Container(
        margin: EdgeInsets.symmetric(horizontal: 16.w),
        padding: EdgeInsets.all(20.w),
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20.r),
        ),
        child: Column(
          children: [
            // 卡路里数值和日期
            Obx(() => Column(
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.end,
                      children: [
                        Text(
                          '${controller.state.totalCalories.value.toInt()}',
                          style: TextStyle(
                            fontSize: 48.sp,
                            fontWeight: FontWeight.bold,
                            color: Colors.white,
                          ),
                        ),
                        SizedBox(width: 19.w,),
                        Text(
                          'kcal',
                          style: TextStyle(
                            fontSize: 16.sp,
                            color: Colors.grey[400],
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 8.h),
                    Text(
                      controller.state.currentDateText.value,
                      style: TextStyle(
                        fontSize: 14.sp,
                        color: Colors.grey[400],
                      ),
                    ),
                  ],
                )),

            SizedBox(height: 16.h),

            // 小A管家模块
            Container(
              padding: EdgeInsets.symmetric(vertical: 6.h,horizontal: 18.w),
              height: 56.h,
              decoration: BoxDecoration(
                color: const Color(0xFF282528),
                borderRadius: BorderRadius.circular(8.r),
              ),
              child: Row(
                children: [
                  Text(
                    '小A管家：',
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: Colors.white,
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Expanded(
                    child: Obx(() {
                      // 根据能量平衡显示建议
                      final balance = controller.state.energyBalance.value;
                      String advice = '';
                      
                      return Text(
                        advice,
                        style: TextStyle(
                          fontSize: 13.sp,
                          color: Colors.grey[300],
                        ),
                      );
                    }),
                  ),
                ],
              ),
            ),

            SizedBox(height: 16.h),

            // 图例
            Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                Row(
                  children: [
                    Container(
                      width: 9.w,
                      height: 9.w,
                      decoration: const BoxDecoration(
                        color: Color(0xFFFFB71E),
                        shape: BoxShape.circle,
                      ),
                    ),
                    SizedBox(width: 6.w),
                    Obx(() => Text(
                          '摄入目标 ${controller.state.targetCalories.value.toInt()} kcal',
                          style: TextStyle(
                            fontSize: 12.sp,
                            color: Colors.grey[400],
                          ),
                        )),
                  ],
                ),
              ],
            ),

            SizedBox(height: 24.h),

            // 柱状图
            SizedBox(
              height: 200.h,
              child: Obx(() => _buildCalorieBarChart()),
            ),
          ],
        ),
      ),
    );
  }

  /// 构建卡路里柱状图
  Widget _buildCalorieBarChart() {
    final items = controller.state.chartItems;
    final maxY = controller.state.chartMaxY.value > 0
        ? controller.state.chartMaxY.value
        : 1000.0;
    return Padding(
      padding: EdgeInsets.only(bottom: 8.h),
      child: BarChart(
        BarChartData(
          alignment: BarChartAlignment.spaceAround,
          maxY: maxY,
          barTouchData: BarTouchData(enabled: false),
          titlesData: FlTitlesData(
            show: true,
            bottomTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 50.h,
                getTitlesWidget: (value, meta) {
                  final int index = value.toInt();
                  // 显示时间轴标签
                  if (index == -1) {
                    return Padding(
                      padding: EdgeInsets.only(top: 8.h),
                      child: Text(
                        '00:00',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 10.sp,
                        ),
                      ),
                    );
                  } else if (index == items.length) {
                    return Padding(
                      padding: EdgeInsets.only(top: 8.h),
                      child: Text(
                        '24:00',
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 10.sp,
                        ),
                      ),
                    );
                  } else if (index >= 0 && index < items.length) {
                    final item = items[index];
                    return Padding(
                      padding: EdgeInsets.only(top: 8.h),
                      child: Text(
                        item.mealKey,
                        style: TextStyle(
                          color: Colors.grey[400],
                          fontSize: 10.sp,
                        ),
                      ),
                    );
                  }
                  return const SizedBox();
                },
              ),
            ),
            leftTitles: AxisTitles(
              sideTitles: SideTitles(
                showTitles: true,
                reservedSize: 40.w,
                getTitlesWidget: (value, meta) {
                  return Text(
                    value.toInt().toString(),
                    style: TextStyle(
                      color: Colors.grey[400],
                      fontSize: 10.sp,
                    ),
                  );
                },
              ),
            ),
            topTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
            rightTitles: const AxisTitles(
              sideTitles: SideTitles(showTitles: false),
            ),
          ),
          gridData: const FlGridData(
            show: false,
          ),
          borderData: FlBorderData(
            show: true,
            border: Border(
              bottom: BorderSide(
                color: Colors.grey[800]!,
                width: 1,
              ),
              left: BorderSide(
                color: Colors.grey[800]!,
                width: 1,
              ),
            ),
          ),
          extraLinesData: ExtraLinesData(
            horizontalLines: [
              HorizontalLine(
                y: 0,
                color: Colors.grey[800]!,
                strokeWidth: 1,
              ),
            ],
            verticalLines: [
              // 00:00 标记线
              VerticalLine(
                x: -0.5,
                color: Colors.transparent,
                strokeWidth: 1,
                label: VerticalLineLabel(
                  show: true,
                  alignment: Alignment.bottomCenter,
                  padding: EdgeInsets.only(top: 8.h),
                  style: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 10.sp,
                  ),
                  labelResolver: (line) => '00:00',
                ),
              ),
              // 24:00 标记线
              VerticalLine(
                x: items.length - 0.5,
                color: Colors.transparent,
                strokeWidth: 1,
                label: VerticalLineLabel(
                  show: true,
                  alignment: Alignment.bottomCenter,
                  padding: EdgeInsets.only(top: 8.h),
                  style: TextStyle(
                    color: Colors.grey[400],
                    fontSize: 10.sp,
                  ),
                  labelResolver: (line) => '24:00',
                ),
              ),
            ],
          ),
          barGroups: List.generate(items.length, (index) {
            final item = items[index];
            return BarChartGroupData(
              x: index,
              barRods: [
                BarChartRodData(
                  toY: item.calories,
                  color: const Color(0xFFFFB71E),
                  width: (items.length <= 6 ? 30.w : 18.w),
                  borderRadius: BorderRadius.vertical(
                    top: Radius.circular(20.r),
                  ),
                ),
              ],
            );
          }),
        ),
      ),
    );
  }

  /// 构建今日能量平衡卡片
  Widget _buildEnergyBalanceCard() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color(0xff282528),
        borderRadius: BorderRadius.circular(16.r),
        border: Border.all(
          color: const Color(0xff282528),
          width: 1.0,
        ),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                '今日能量平衡',
                style: TextStyle(
                  fontSize: 16.sp,
                  color: Colors.white,
                  fontWeight: FontWeight.w500,
                ),
              ),
              SizedBox(width: 8.w),
              Obx(() => Container(
                    padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 2.h),
                    decoration: BoxDecoration(
                      color: controller.state.energyBalance.value < 0
                          ? const Color(0xFF4CAF50)
                          : const Color(0xFFED5C2F),
                      borderRadius: BorderRadius.circular(4.r),
                    ),
                    child: Text(
                      controller.state.energyBalance.value < 0 ? '缺口' : '增肌',
                      style: TextStyle(
                        fontSize: 12.sp,
                        color: Colors.white,
                      ),
                    ),
                  )),
            ],
          ),
          SizedBox(height: 16.h),
          Obx(() => Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    controller.state.energyBalance.value >= 0 ? '+' : '',
                    style: TextStyle(
                      fontSize: 36.sp,
                      fontWeight: FontWeight.bold,
                      color: controller.state.energyBalance.value < 0
                          ? const Color(0xFF4CAF50)
                          : const Color(0xFFED5C2F),
                    ),
                  ),
                  Text(
                    '${controller.state.energyBalance.value.toInt()}',
                    style: TextStyle(
                      fontSize: 36.sp,
                      fontWeight: FontWeight.bold,
                      color: controller.state.energyBalance.value < 0
                          ? const Color(0xFF4CAF50)
                          : const Color(0xFFED5C2F),
                    ),
                  ),
                  SizedBox(width: 8.w),
                  Text(
                    'Kcal',
                    style: TextStyle(
                      fontSize: 16.sp,
                      color: Colors.grey[400],
                    ),
                  ),
                ],
              )),
          SizedBox(height: 24.h),
          
          // 进度条
          Stack(
            alignment: Alignment.center,
            children: [
              Container(
                height: 8.h,
                decoration: BoxDecoration(
                  color: Colors.grey[800],
                  borderRadius: BorderRadius.circular(4.r),
                ),
              ),
              Obx(() {
                final progress = controller.state.totalCalories.value /
                    controller.state.targetCalories.value;
                final clampedProgress = progress.clamp(0.0, 1.0);
                return Align(
                  alignment: Alignment.centerLeft,
                  child: FractionallySizedBox(
                    widthFactor: clampedProgress,
                    child: Container(
                      height: 8.h,
                      decoration: BoxDecoration(
                        color: const Color(0xFF4CAF50),
                        borderRadius: BorderRadius.circular(4.r),
                      ),
                    ),
                  ),
                );
              }),
              Obx(() {
                final progress = controller.state.totalCalories.value /
                    controller.state.targetCalories.value;
                return Positioned(
                  left: (progress * MediaQuery.of(Get.context!).size.width * 0.85)
                      .clamp(0.0, MediaQuery.of(Get.context!).size.width * 0.85),
                  child: Container(
                    width: 2.w,
                    height: 16.h,
                    color: Colors.blue,
                  ),
                );
              }),
            ],
          ),
          SizedBox(height: 8.h),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '盈余',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                ),
              ),
              Text(
                '缺口',
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                ),
              ),
            ],
          ),
          SizedBox(height: 24.h),
          
          // 说明文字
          Container(
            padding: EdgeInsets.all(12.w),
            decoration: BoxDecoration(
              color: Colors.black.withValues(alpha: 0.3),
              borderRadius: BorderRadius.circular(12.r),
            ),
            child: Obx(() {
              final data = controller.state.energyBalanceData.value;
              final balance = controller.state.energyBalance.value;
              String advice = '';
              if (balance < -200) {
                advice = '能量平衡=摄入卡路里-消耗卡路里\n缺口：摄入＜消耗，有助于减重。\n盈余：摄入＞消耗，有助于增肌。';
              } else if (balance > 200) {
                advice = '能量平衡=摄入卡路里-消耗卡路里\n缺口：摄入＜消耗，有助于减重。\n盈余：摄入＞消耗，有助于增肌。';
              } else {
                advice = '能量平衡=摄入卡路里-消耗卡路里\n缺口：摄入＜消耗，有助于减重。\n盈余：摄入＞消耗，有助于增肌。';
              }
              return Text(
                advice,
                style: TextStyle(
                  fontSize: 12.sp,
                  color: Colors.grey[400],
                  height: 1.5,
                ),
              );
            }),
          ),
          
          SizedBox(height: 24.h),
          
          // 饮食摄入和活动消耗
          Row(
            children: [
              // 饮食摄入
              Expanded(
                child: Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.circular(24.r),
                    border: Border.all(
                      color: const Color(0xFF3A3A3A),
                      width: 1,
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '饮食摄入',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFF4CAF50),
                        ),
                      ),
                      SizedBox(height: 12.h),
                      Obx(() => Row(
                            crossAxisAlignment: CrossAxisAlignment.baseline,
                            textBaseline: TextBaseline.alphabetic,
                            children: [
                              Text(
                                '${controller.state.totalCalories.value.toInt()}',
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: 8.w),
                              Text(
                                'kcal',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          )),
                      SizedBox(height: 16.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.proteinKcal ?? 0;
                        return _buildNutrientRow('蛋白质', '$value Kcal');
                      }),
                      SizedBox(height: 8.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.carbohydrateKcal ?? 0;
                        return _buildNutrientRow('碳水化合物', '$value Kcal');
                      }),
                      SizedBox(height: 8.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.fatKcal ?? 0;
                        return _buildNutrientRow('脂肪', '$value Kcal');
                      }),
                    ],
                  ),
                ),
              ),

              SizedBox(width: 16.w),

              // 活动消耗
              Expanded(
                child: Container(
                  padding: EdgeInsets.all(16.w),
                  decoration: BoxDecoration(
                    color: Colors.transparent,
                    borderRadius: BorderRadius.circular(24.r),
                    border: Border.all(
                      color: const Color(0xFF3A3A3A),
                      width: 1,
                    ),
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '活动消耗',
                        style: TextStyle(
                          fontSize: 14.sp,
                          color: const Color(0xFFED5C2F),
                        ),
                      ),
                      SizedBox(height: 12.h),
                      Obx(() => Row(
                            crossAxisAlignment: CrossAxisAlignment.baseline,
                            textBaseline: TextBaseline.alphabetic,
                            children: [
                              Text(
                                '${controller.state.activityCalories.value.toInt()}',
                                style: TextStyle(
                                  fontSize: 28.sp,
                                  fontWeight: FontWeight.bold,
                                  color: Colors.white,
                                ),
                              ),
                              SizedBox(width: 8.w),
                              Text(
                                'kcal',
                                style: TextStyle(
                                  fontSize: 14.sp,
                                  color: Colors.grey[500],
                                ),
                              ),
                            ],
                          )),
                      SizedBox(height: 16.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.basalMetabolism ?? 0;
                        return _buildNutrientRow('基础代谢', '$value Kcal');
                      }),
                      SizedBox(height: 8.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.sportKcal ?? 0;
                        return _buildNutrientRow('运动消耗', '$value Kcal');
                      }),
                      SizedBox(height: 8.h),
                      Obx(() {
                        final data = controller.state.energyBalanceData.value;
                        final value = data?.dailyKcal ?? 0;
                        return _buildNutrientRow('日常活动', '$value Kcal');
                      }),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }



  /// 构建营养素行
  Widget _buildNutrientRow(String label, String value) {
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        Text(
          label,
          style: TextStyle(
            fontSize: 11.sp,
            color: Colors.grey[500],
          ),
        ),
        Text(
          value,
          style: TextStyle(
            fontSize: 11.sp,
            color: Colors.white,
          ),
        ),
      ],
    );
  }

  /// 构建关于饮食卡片
  Widget _buildAboutDietCard() {
    return Container(
      margin: EdgeInsets.symmetric(horizontal: 16.w),
      padding: EdgeInsets.all(20.w),
      decoration: BoxDecoration(
        color: const Color.fromRGBO(3, 0, 3, 1),
        borderRadius: BorderRadius.circular(20.r),
        border: Border.all(
          color: const Color.fromRGBO(33, 33, 33, 1),
          width: 1.0,
        ),
      ),
      child: Row(
        children: [
          Container(
            width: 40.w,
            height: 40.w,
            decoration: const BoxDecoration(
              color: Color(0xFF282528),
              shape: BoxShape.circle,
            ),
            child: const Icon(
              Icons.info_outline,
              color: Colors.white,
              size: 24,
            ),
          ),
          SizedBox(width: 12.w),
          Expanded(
            child: Text(
              '关于饮食',
              style: TextStyle(
                fontSize: 16.sp,
                color: Colors.white,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
          Icon(
            Icons.arrow_forward_ios,
            color: Colors.grey[400],
            size: 16.sp,
          ),
        ],
      ),
    );
  }
}
